// pages/cart/cart.js
const db = wx.cloud.database();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    carts:[],               // 购物车列表
    cartList:[],
    producttList:[],
    hasList:false,          // 列表是否有数据
    totalPrice:0,           // 总价，初始为0
    selectAllStatus:true,    // 全选状态，默认全选
    obj:{
        name:"hello"
    },


  },
  /**
   * 查出登录用户的所有购物车
   */
  getcartbyuserid(){
    //获取storage中登录的用户信息
    var user = wx.getStorageSync('user')
    console.log(user);
    db.collection("cart").where({
      userId:user._id
    }).get({
      success:res=>{
        // console.log(res.data);
        this.setData({
          cartList:res.data
        })
        this.jiexi();
        console.log(this.data.carts);
        return {
          carts:this.data.carts
        }
        console.log(this.data.cartList);
        // console.log(this.data.producttList);
      }
    })
  },

  /**
   * 解析
   */
  jiexi() {
    if (this.data.cartList.length != 0) {
      // const cart = [];
      this.data.cartList.forEach((element) => {
        db.collection("product")
          .doc(element.productId)
          .get({
            success: (res1) => {
              const product = {
                id: res1.data._id,
                name: res1.data.name,
                imageUrl: res1.data.imageUrl,
                price: res1.data.price,
                buyCount: element.buyCount,
                selected: true,
              };
              // cart.push(product);
              console.log(product);
              this.setData({
                carts:this.data.carts.concat(product),
                hasList:true
              });
              // 计算总价
              this.getTotalPrice()
              console.log(this.data.carts)
            },
          });
      });
    }
  },

  //跳转到支付页面
  gotopay(){
    if(this.data.carts.length!=0&&this.data.totalPrice!=0){
      // var cartsto = JSON.stringify(this.data.carts)
      wx.navigateTo({
        url: "/pages/order/order?totalPrice="+this.data.totalPrice+"&carts="+encodeURIComponent(JSON.stringify(this.data.carts))
      })
    }

  },
  //跳转到地址修改页面
  gotoaddress(){
    wx.navigateTo({
      url: '../address/address'
    })
  },
  gotohome(){
    wx.switchTab({
      url: '../home/home'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getcartbyuserid();

    console.log(4);
  },
  



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //判断用户是否登录
    if(wx.getStorageSync('user')){
      this.setData({
        isLogin:true
      })
    }else{
      this.setData({
        isLogin:false
      })
      wx.showModal({
        title: '请先登录',
        content: '点击跳转登录页面',
        success (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login',
            })
          } else if (res.cancel) {
            console.log('用户点击取消')
            wx.navigateTo({
              url: '/pages/login/login',
            })
          }
        }
      })
    }
  },
  /**
   * 当前商品选中事件
   */
  selectList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    const selected = carts[index].selected;
    carts[index].selected = !selected;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },
  /**
   * 删除购物车当前商品
   */
  deleteList(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    carts.splice(index,1);
    this.setData({
      carts: carts
    });
    if(!carts.length){
      this.setData({
        hasList: false
      });
    }else{
      this.getTotalPrice();
    }
  },

  /**
   * 购物车全选事件
   */
  selectAll(e) {
    let selectAllStatus = this.data.selectAllStatus;
    selectAllStatus = !selectAllStatus;
    let carts = this.data.carts;

    for (let i = 0; i < carts.length; i++) {
      carts[i].selected = selectAllStatus;
    }
    this.setData({
      selectAllStatus: selectAllStatus,
      hasList:true,
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 绑定加数量事件
   */
  addCount(e) {
    const index = e.currentTarget.dataset.index;
    let carts = this.data.carts;
    let buyCount = carts[index].buyCount;
    buyCount = buyCount + 1;
    carts[index].buyCount = buyCount;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 绑定减数量事件
   */
  minusCount(e) {
    const index = e.currentTarget.dataset.index;
    const obj = e.currentTarget.dataset.obj;
    let carts = this.data.carts;
    let buyCount = carts[index].buyCount;
    if(buyCount <= 1){
      return false;
    }
    buyCount = buyCount - 1;
    carts[index].buyCount = buyCount;
    this.setData({
      carts: carts
    });
    this.getTotalPrice();
  },

  /**
   * 计算总价
   */
  getTotalPrice() {
    let carts = this.data.carts;                  // 获取购物车列表
    let total = 0;
    for(let i = 0; i<carts.length; i++) {         // 循环列表得到每个数据
      if(carts[i].selected) {                     // 判断选中才会计算价格
        total += carts[i].buyCount * carts[i].price;   // 所有价格加起来
      }
    }
    this.setData({                                // 最后赋值到data中渲染到页面
      carts: carts,
      totalPrice: total.toFixed(2)
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    wx.stopPullDownRefresh()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})